#include "dataanalysis.h"
#include "core/databasepool/databasepool.h"
#include <QSqlQuery>
#include <QVariant>

// 构造函数
DataAnalysis::DataAnalysis(QObject* parent) : QObject(parent) {}

// 析构函数
DataAnalysis::~DataAnalysis() {}

// 分析数据
void DataAnalysis::analyzeData(int deviceId, const QDateTime& startTime, const QDateTime& endTime) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    // 准备查询指定时间段内设备数据的SQL语句
    query.prepare("SELECT temperature, humidity, light, co2, pressure FROM data WHERE device_id = :device_id AND timestamp BETWEEN :startTime AND :endTime");
    query.bindValue(":device_id", deviceId);
    query.bindValue(":startTime", startTime.toString("yyyy-MM-dd hh:mm:ss"));
    query.bindValue(":endTime", endTime.toString("yyyy-MM-dd hh:mm:ss"));
    if (query.exec()) {
        while (query.next()) {
            double temperature = query.value(0).toDouble();
            double humidity = query.value(1).toDouble();
            double light = query.value(2).toDouble();
            double co2 = query.value(3).toDouble();
            double pressure = query.value(4).toDouble();
            // 这里可以添加具体的数据分析逻辑
        }
    }
    DatabasePool::instance().releaseConnection(db);
}

QList<QSqlRecord> DataAnalysis::queryHistoricalData(int deviceId, const QDateTime& startTime, const QDateTime& endTime) {
    QList<QSqlRecord> records;
    QSqlDatabase db = DatabasePool::instance().getConnection();
    QSqlQuery query(db);
    query.prepare("SELECT * FROM data WHERE device_id = ? AND timestamp BETWEEN ? AND ?");
    query.addBindValue(deviceId);
    query.addBindValue(startTime.toString("yyyy-MM-dd hh:mm:ss"));
    query.addBindValue(endTime.toString("yyyy-MM-dd hh:mm:ss"));
    if (query.exec()) {
        while (query.next()) {
            records.append(query.record());
        }
    }
    return records;
    DatabasePool::instance().releaseConnection(db);
}

// 生成趋势图和报告（这里只是占位，具体实现需要图形库）
void DataAnalysis::generateTrendGraphAndReport(int deviceId, const QDateTime& startTime, const QDateTime& endTime) {
    QSqlDatabase db = DatabasePool::instance().getConnection();
    // 这里可以添加生成趋势图和报告的具体逻辑
    DatabasePool::instance().releaseConnection(db);
}
